<template>
	<view class="">
		<view class="container" v-if="scene || classType === 3">
			<u-navbar leftIcon=" " :title="stock.wxTitle || ''" :placeholder="true" />

			<!-- <view :style="{ textAlign: classifyConfig.setStyle.linkPosition }" class="title" v-if="classifyConfig.setStyle.linkName">
        店铺名称：{{ classifyConfig.setStyle.linkName }}
      </view> -->

			<view class="title" v-if="classifyConfig && classifyConfig.setStyle.linkName">桌台名称：{{ stock.deskNumber }}</view>

			<!-- 单列模式start -->
			<view class="main" v-if="classifyConfig && !classifyConfig.setStyle.linkType">
				<!-- 左侧菜单 begin -->
				<scroll-view
					class="menu-bar"
					scroll-y
					scroll-with-animation
					:scroll-top="categoryTop"
					:style="{
						height: cart.length > 0 || requireCart.length > 0 ? 'calc(100vh - 280rpx)' : 'calc(100vh - 190rpx)'
					}"
				>
					<view class="wrapper">
						<view
							class="menu-item"
							:id="`category-${category.id}`"
							@tap="handleMenuSelected(category.id)"
							:class="{ active: currentCategoryId === category.id }"
							v-for="(category, index) in categories"
							:key="index"
						>
							<!-- <image :src="category.category_image_url" class="image" mode="widthFix"></image> -->
							<view class="title">{{ category.name }}</view>
						</view>
					</view>
				</scroll-view>
				<!-- 左侧菜单 end -->
				<!-- 右侧商品列表 begin -->
				<scroll-view class="product-section" style="height: 100%" scroll-y scroll-with-animation :scroll-top="productsScrollTop" @scroll="productsScroll">
					<view class="wrapper">
						<!-- 商品 begin -->
						<view class="products-list" v-for="(category, index) in categories" :key="index" :id="`products-${category.id}`">
							<view class="category-name">{{ category.name }}</view>
							<view v-if="category.upIcon" class="category-banner" @click="goRecommendActivity(category.url)">
								<!-- 分类图片 -->
								<image style="width: 534rpx; height: 175rpx; border-radius: 10rpx" lazy-load :src="category.upIcon" mode=""></image>
							</view>
							<view class="products">
								<!-- <view class="product" v-for="(product, key) in category.items" :key="key"
									@tap="showProductDetailModal(product)"> -->
								<view class="product" v-for="(product, key) in category.items" :key="key" @tap="goProductDetail(product)">
									<view class="mask" v-if="product.isSoldOut">
										<image src="@/static/images/classify/soldOut.png" mode="" style="width: 100rpx; height: 100rpx; margin-left: 30rpx"></image>
									</view>
									<view style="width: 170rpx; height: 170rpx; margin-right: 10rpx">
										<image
											lazy-load
											:src="product.image ? product.image : '../../../static/images/classify/imgs.png'"
											style="height: 100%; width: 100%; border-radius: 10rpx"
											class="image"
										></image>
									</view>
									<!-- <image :src="product.image" mode="aspectFit" class="image"></image> -->
									<view class="content" style="justify-content: flex-start">
										<!-- <view class="name" v-if="product.name">{{ product.name.length > 10 ? product.name.slice(0, 10) + '...' : product.name }}</view> -->
										<view class="name" v-if="product.name">{{ product.name }}</view>
										<!-- <view class="guqing" v-if="product.isShowSold">剩余：{{ product.fGuQing }}</view> -->
										<view class="fsize-24 line-gray-6 mt-10" v-if="product.description">
											{{ product.description.length > 12 ? product.description.slice(0, 12) + '...' : product.description || product.spec }}
										</view>

										<view class="price" style="flex: 1; align-items: flex-end">
											<!-- 会员价start -->
											<view>
												<view class="price-box">
													<text class="vip-price" style="line-height: 1em; margin-top: 8rpx">
														<text style="font-size: 22rpx; color: #111">￥</text>
														<text style="font-size: 30rpx; color: #111">
															{{ product.realPrice }}
														</text>
													</text>

													<text
														class="realprice"
														style="margin-left: 6rpx"
														v-if="product.showPrice"
														:class="{ isVip: userInfo.id && product.showPriceName === '原价' }"
													>
														￥{{ product.showPrice }}
													</text>

													<bubble-box
														v-if="product.showPrice && product.showPriceName !== '原价'"
														color="#edac2f"
														:title="product.showPriceName"
														bg-color="linear-gradient(0deg, #111111, #333333)"
													/>
												</view>
											</view>
											<!-- 会员价end -->

											<view style="height: 44rpx" v-if="!product.isSoldOut">
												<image src="/static/images/common/round_add_normal.png" class="add-btn" @click.stop="showProductDetailModal(product)"></image>
												<view class="number-badge" v-show="productCartNum(product.id)">
													<view class="number">{{ productCartNum(product.id) }}</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<!-- 商品 end -->
					</view>
				</scroll-view>

				<!-- 右侧商品列表 end -->
			</view>
			<!-- 单列模式 emd -->

			<!-- 宫格模式 start 😟😟😟-->
			<view class="main grid-container" v-else>
				<view class="grid-open-btn">
					<!-- @touchmove="btnMove" :style="{ top: top, left: left }"-->
					<u-icon size="25px" @click="onGridShow(true)" name="list"></u-icon>
				</view>
				<scroll-view
					class="grid-product-section"
					:style="{
						height: cart.length > 0 ? 'calc(100vh - 280rpx)' : 'calc(100vh - 250rpx)'
					}"
					scroll-y
					scroll-with-animation
					:scroll-top="productsScrollTop"
					@scroll="productsScroll"
				>
					<view class="grid-list" v-for="(category, index) in categories" :key="index" :id="`products-${category.id}`">
						<view class="category-name">{{ category.name }}</view>
						<view v-if="category.upIcon" class="category-banner" @click="goRecommendActivity(category.url)">
							<!-- 分类图片 -->
							<image style="width: 100%; height: 175rpx; border-radius: 10rpx" :src="category.upIcon" mode="aspectFill"></image>
						</view>
						<view class="grid-wrapper">
							<view class="grid-products-list" v-for="(product, key) in category.items" :key="key" @tap="goProductDetail(product)">
								<view style="width: 100%; height: 200rpx">
									<image
										lazy-load
										:src="product.image ? product.image : '../../../static/images/classify/imgs.png'"
										style="border-radius: 10rpx; width: 100%; height: 100%"
										mode="aspectFill"
									/>
								</view>
								<view class="grid-item-info">
									<view class="grid-name" style="padding-left: 10rpx" v-if="product.name">
										{{ product.name.length > 8 ? product.name.slice(0, 8) + '...' : product.name }}
									</view>
									<!-- 	<view class="grid-name" style="padding-left: 10rpx; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">
										{{ product.name }}
									</view> -->
									<!-- mt-4 -->

									<view class="fsize-24 line-gray-6 ellipsis" style="padding-left: 10rpx; margin-top: 10rpx">
										{{ (product.description.length > 12 ? product.description.slice(0, 12) + '...' : product.description) || product.spec }}
									</view>
									<view class="price" style="padding: 0 10rpx; align-items: flex-end" :style="{ padding: product.showPrice ? '' : '30rpx' }">
										<view>
											<view class="price-box" v-if="product.showPrice">
												<!-- <bubble-box
													v-if="product.showPrice"
													color="#edac2f"
													:title="product.showPriceName"
													bg-color="linear-gradient(0deg, #111111, #333333)"
												/> -->
												<text class="realprice" v-if="product.showPrice" :class="{ isVip: userInfo.id && product.showPriceName === '原价' }">
													￥{{ product.showPrice }}
												</text>
												<bubble-box :title="product.showPriceName"></bubble-box>
											</view>
											<!-- <text class="vip-box" v-if="product.vipPrice > 0">
												<text>会员价</text>
												￥{{ product.vipPrice }}
											</text> -->
											<view>
												<text class="vip-price">
													<text style="font-size: 22rpx">￥</text>
													<text>{{ product.realPrice }}</text>
												</text>
												<!--  <text class="vip-box" v-if="product.vipPrice > 0">
                          <text>会员价</text>
                          ￥{{ product.vipPrice }}
                        </text> -->
											</view>
										</view>
										<!-- :materials-btn="!product.is_single" -->
										<!-- 不要文字，直接加号小图标展示sku -->
										<view style="position: relative; height: 44rpx">
											<image src="/static/images/common/round_add_normal.png" class="add-btn" @click.stop="showProductDetailModal(product)"></image>
											<view class="number-badge" style="right: -14rpx; top: -20rpx" v-show="productCartNum(product.id)">
												<view class="number">{{ productCartNum(product.id) }}</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- </view> -->
				</scroll-view>
			</view>
			<!-- 宫格模式 end -->

			<!-- 商品详情 modal end -->

			<!-- 购物车栏 begin -->
			<cart-bar :requireCart="requireCart" :cart="cart" @add="handleAddToCart" @minus="handleMinusFromCart" @clear="clearCart" @pay="pay" @onOrder="onOrder" />
			<!-- 购物车栏 end -->

			<!-- 登录popup -->
			<login-popup ref="loginPopup"></login-popup>
		</view>

		<!-- 未扫码点击按钮唤起扫码 -->
		<view class="container" v-else @click="scanCode">
			<u-navbar leftIcon=" " :title="stock.wxTitle || ''" :placeholder="true" />
			<!-- <button>扫码点餐</button> -->
			<view class="scan-btn">
				<image style="margin-bottom: 20rpx" src="/static/images/classify/scan.png" mode="aspectFit"></image>
				<u-button type="primary" icon="scan" text="扫码点餐"></u-button>
			</view>
		</view>

		<!-- 商品详情 modal begin -->
		<product-popup
			:materialsOtherData="materialsOtherData"
			:product="product"
			:visible="productModalVisible"
			@cancel="closeProductDetailModal"
			@add-to-cart="handleAddToCartInModal"
		/>

		<!-- 宫格模式的分类列表 -->
		<u-popup :show="gridShow" @close="onGridShow(false)" mode="left" bgColor="transparent">
			<view class="grid-box">
				<scroll-view style="height: 60%; padding-top: 80rpx; width: 100%" class="menu-bar" scroll-y scroll-with-animation :scroll-top="categoryTop">
					<view class="wrapper">
						<view
							class="menu-item"
							:id="`category-${category.id}`"
							@tap="handleMenuSelected(category.id)"
							:class="{ active: currentCategoryId === category.id }"
							v-for="(category, index) in categories"
							:key="index"
						>
							<view class="title">{{ category.name }}</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import Actions from './components/actions/actions.vue';
import CartBar from './components/cartbar/cartbar.vue';
import productPopup from './components/product-popup/product-popup.vue';
import cartPopup from './components/cart-popup/cart-popup.vue';
// import BubbleBox from '@/components/bubble-box/bubble-box.vue'; BubbleBox

export default {
	components: {
		Actions,
		CartBar,
		productPopup,
		cartPopup
	},
	data() {
		return {
			/* top: 50 + '%', // 宫格模式按钮
      left: 0, // 宫格模式按钮 */
			deskId: 0,
			orderId: 0,
			categories: [],
			cart: [],
			requireCart: [],
			product: {},
			currentCategoryId: 0, // 左侧分类显示高亮的盒子
			notices: [],
			productModalVisible: false,
			cartPopupShow: false,
			productsScrollTop: 0,
			showSearch: false,
			categoryTop: 0,
			gridShow: false,
			materialsOtherData: {}
		};
	},
	computed: {
		...mapState(['orderType', 'address', 'isLogin', 'stock', 'scene', 'classType', 'userInfo']),
		...mapState('classify', ['classifyConfig']),
		productCartNum(id) {
			//计算单个饮品添加到购物车的数量
			return (id) =>
				this.cart.reduce((acc, cur) => {
					if (cur.FFoodID == id) {
						return (acc += cur.number);
					}
					return acc;
				}, 0);
		}
	},
	onLoad(opt) {
		// this.scanCode()
		// this.deskId = uni.getStorageSync('deskId') || 0
		// this.orderId = uni.getStorageSync('orderId') || 0
		// this.getClassifyList()
		this.scanCode();
	},
	onShow() {
		// if(this.classType !== 3 && this.scene)
		// 扫码存在 或者 外卖就调用购物车
		if (this.scene || this.classType === 3) {
			this.deskId = uni.getStorageSync('deskId') || 0;
			this.orderId = uni.getStorageSync('orderId') || 0;
			this.getClassifyList();
		}
	},

	methods: {
		...mapMutations(['SET_ORDER_TYPE', 'SET_SCENE', 'SET_STOCK', 'SET_PAGEDATA', 'SET_LOGIN', 'SET_POPUP']),
		...mapMutations('classify', ['SET_ClassifyConfig']),
		...mapMutations('quantity', ['SET_CANTEENDATA']),
		// 扫码
		async scanCode() {
			const app = getApp().globalData;
			const that = this;
			// 唤起扫码
			if (that.classType !== 3 && !that.scene) {
				// classType是吃饭模式
				await uni.scanCode({
					// scanType: ['barCode', 'qrCode', 'datamatrix', 'pdf417'],
					async success(res) {
						console.log(res);
						let scene = '';
						if (res.path && res.scanType.slice(0, 2) !== 'QR') {
							if (res.path.slice(0, 13) === 'pages/tab_bar') {
								scene = res.path.slice(26);
							} else {
								scene = res.path.slice(38);
							}
						} else {
							const scanCode = res.result.slice(res.result.indexOf('=') + 1);
							const result = await that.$api.getCodeDeskInfo({ id: scanCode });
							scene = result.data.deskId + ',' + result.data.storeId;
						}
						// if (res.path.slice(0, 13) === 'pages/tab_bar') {
						//   scene = res.path.slice(26);
						// } else if (res.scanType === 'QR_CODE') {
						//   const scanCode = res.result.slice(res.result.indexOf('=') + 1);
						//   console.log(scanCode, 'scanCode');
						//   const result = await that.$api.getCodeDeskInfo({ id: scanCode });
						//   scene = result.data.deskId + ',' + result.data.storeId;
						// } else {
						//   scene = res.path.slice(38);
						// }
						that.SET_SCENE(scene);
						app.change = true;
						uni.redirectTo({
							url: '/pages/canteen/quantity/quantity'
						});
						// 获取首页信息
						that.$api
							.GetDesignPageData({
								code: 'mobile_food',
								scene
							})
							.then((res) => {
								that.SET_STOCK(res.otherData); // 存储的stock
								that.SET_PAGEDATA(res.data.items); // 首页信息
								that.SET_POPUP(res.data.popUp || {}); // 首页信息
								that.SET_ClassifyConfig(res.data.classifyConfigData);
								that.SET_CANTEENDATA(res.data.canteenConfig); // 开台页配置
							});
					},
					fail(err) {
						console.log(err);
					}
				});
				return;
			}
		},
		calcSize() {
			let h = 0;
			// 遍历购物车左侧数据，计算顶部距离
			this.categories.forEach((item) => {
				let view = uni.createSelectorQuery().select(`#products-${item.id}`); // id选择器，选中对应的id
				view.fields(
					{
						// fields 获取指定字段，size是height和width的意思
						size: true
					},
					(data) => {
						if (!data) return;
						item.top = h;
						h += Math.floor(data.height);
						item.bottom = h;
					}
				).exec(); // 方法用于执行选择器查询并调用之前设置的回调函数。
			});

			let categoryH = 0;
			this.categories.forEach((v) => {
				let views = uni.createSelectorQuery().select(`#category-${v.id}`);
				views
					.fields({ size: true }, (data) => {
						if (!data) return;
						v.categoryTop = categoryH;
						categoryH += Math.floor(data.height);
						v.categoryBottom = categoryH;
					})
					.exec();
			});
		},
		// 获取购物车数据
		getClassifyList() {
			let _this = this;
			console.log(_this.stock.id);
			_this.$api
				.GetClassifyList({
					storeId: _this.stock.id
				})
				.then((res) => {
					// console.log(res);
					_this.categories = res.data;

					_this.currentCategoryId = _this.categories.length && _this.categories[0].id; // 左侧显示的高亮的的id，categories数据有就是用后面的
					_this.$nextTick(() => _this.calcSize());
					// if (_this.isLogin) {
					// 获取购物车数据
					_this.$api
						.GetShoppingCart({
							categoriesId: _this.categories[0].id,
							storeId: _this.stock.id,
							deskId: this.deskId,
							orderId: this.orderId
						})
						.then((res) => {
							// console.log(res);
							if (res.otherData.payStatus) {
								// 状态清除拦截到选桌台
								uni.removeStorageSync('deskId');
								uni.removeStorageSync('orderId');
								uni.redirectTo({
									url: '/pages/canteen/quantity/quantity'
								});
							}
							_this.updateCart(res.data.foodList);
							this.requireCart = res.data.defaultList || [];
						});
					// }
				});
		},
		handleAddToCart(product) {
			//添加到购物车
			this.$api
				.AddShoppingCart({
					FFoodID: product.FFoodID || product.id,
					FQty: product.number || 1,
					feed_ids: product.feed_ids || [],
					tast_ids: product.tast_ids || [],
					FFoodSpecID: product.FFoodSpecID || product.specId,
					deskId: this.deskId,
					orderId: this.orderId,
					foodType: product.foodType,
					FShoppingCartID: product.foodType === 2 ? product.FShoppingCartID : 0
				})
				.then((res) => {
					this.updateCart(res.data.foodList);
				});
		},
		handleMinusFromCart(product) {
			//从购物车减商品
			this.$api
				.AddShoppingCart({
					FFoodID: product.FFoodID || product.id,
					FQty: -1,
					feed_ids: product.feed_ids || [],
					tast_ids: product.tast_ids || [],
					FFoodSpecID: product.FFoodSpecID || product.specId,
					deskId: this.deskId,
					orderId: this.orderId,
					foodType: product.foodType,
					FShoppingCartID: product.foodType === 2 ? product.FShoppingCartID : 0
				})
				.then((res) => {
					this.updateCart(res.data.foodList);
				});
		},
		// 更新购物车
		updateCart(data) {
			this.cart =
				data.length === 0
					? []
					: data.map((im) => {
							return {
								description: im.description,
								vipPrice: im.vipPrice, // 会员价格
								FItemID: im.fSubItemID,
								FFoodID: im.fFoodID,
								FName: im.fName,
								FPosPrice: im.fPosPrice,
								number: im.fQty,
								FPic: im.fProImage,
								FSpec: im.fSpec,
								FFoodSpecID: im.fFoodSpecID,
								FRemark: im.fRemark,
								FeedTasteNames: im.feedTasteNames,
								FShoppingCartID: im.fShoppingCartID || 0,
								feed_ids: im.feedData.length > 0 ? im.feedData.map((jm) => jm.fFeedID) : [],
								tast_ids: im.tastData.length > 0 ? im.tastData.map((jm) => jm.fTastID) : [],
								detailList: im.detailList ? im.detailList || [] : [],
								foodType: im.foodType || 0
							};
					  });
		},
		// 获取产品规格
		showProductDetailModal(product) {
			// console.log(product);
			if (product.type === 2) {
				uni.navigateTo({
					url: '/pages/product/product_detail?productId=' + product.id
				});
				return;
			}
			if (product.fGuQing === 0) {
				if (product.specflag === 1) {
					// 获取产品规格
					this.$api
						.GetSpecBySubId({
							FSubItemID: product.id,
							storeId: this.stock.id
						})
						.then((res) => {
							this.product = product;
							this.product.materials = res.data;
							this.materialsOtherData = res.otherData;
						});
				} else {
					this.product = product;
				}
				this.productModalVisible = true;
			}
		},
		handleAddToCartInModal(product) {
			this.handleAddToCart(product);
			this.closeProductDetailModal();
		},
		closeProductDetailModal() {
			this.productModalVisible = false;
			this.product = {};
		},
		openCartDetailsPopup() {
			this.$refs['cartPopup'].open();
		},
		clearCart() {
			this.$api
				.DelCart({
					deskId: this.deskId
				})
				.then((res) => {
					this.cart = [];
				});
		},
		handleMenuSelected(id) {
			this.productsScrollTop = this.categories.find((item) => item.id === id).top; // 获取到当前元素，并将scroll-top的高度设置为它的高度
			// console.log(this.categories.find(item => item.id === id).top);
			this.$nextTick(() => (this.currentCategoryId = id));
		},
		productsScroll({ detail }) {
			const { scrollTop } = detail;
			let tabs = this.categories.filter((item) => item.top <= scrollTop).reverse();
			if (tabs.length > 0) {
				this.currentCategoryId = tabs[0].id;
				this.categoryTop = tabs[0].categoryTop;
			}
		},
		pay() {
			uni.navigateTo({
				url: '/pages/order/pay'
			});
			// uni.redirectTo({
			//   url: '/pages/order/pay'
			// });
		},
		// 立即下单
		onOrder() {
			uni.navigateTo({
				url: '/pages/order/confirm'
			});
			// uni.redirectTo({
			//     url: '/pages/order/confirm'
			//   });
		},
		goProductDetail(item) {
			if (item.isSoldOut) {
				return;
			}
			this.$u.route('/pages/product/product_detail', { productId: item.id });
		},
		goRecommendActivity(path) {
			// 判断分类推荐图片跳转路径
			if (path) {
				uni.navigateTo({
					url: path
				});
			}
		},
		// 关闭宫格弹出层
		onGridShow(show) {
			this.gridShow = show;
		}
		/*  btnMove(e) {
      // 宫格模式按钮移动事件
      // 获取屏幕尺寸
      e.preventDefault();
      const screenWidth = uni.getSystemInfoSync().screenWidth;
      const screenHeight = uni.getSystemInfoSync().screenHeight;
      // this.top = e.changedTouches[0].clientY + 'px';
      this.top = e.changedTouches[0].clientY > screenHeight - 80 ? screenHeight - 80 + 'px' : e.changedTouches[0].clientY < 40 ? 40 + 'px' : e.changedTouches[0].clientY + 'px';
      this.left = e.changedTouches[0].clientX > screenWidth - 40 ? screenWidth - 40 + 'px' : e.changedTouches[0].clientX < 0 ? 0 + 'px' : e.changedTouches[0].clientX + 'px';
      // this.left = Math.max(40, Math.min(this.left, screenWidth - 40)) + 'px';
      // this.left = e.changedTouches[0].clientX + 'px';
    } */
	}
};
</script>

<style lang="scss">
@import './classify.scss';

.add-btn {
	width: 44rpx;
	height: 44rpx;
}

.number-badge {
	z-index: 4;
	position: absolute;
	right: -16rpx;
	// top: 100rpx;
	top: 100rpx;
	background-color: #fff;
	border-radius: 100%;
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;

	.number {
		font-size: 20rpx;
		flex-shrink: 0;
		background-color: #ec3e40;
		color: #fff;
		width: 30rpx;
		height: 30rpx;
		line-height: 30rpx;
		text-align: center;
		border-radius: 100%;
	}
}

.vip-price {
	font-size: 34rpx;
	color: #ed4d4f;
	font-weight: normal;
}
.price-box {
	display: flex;
	align-items: flex-end;
	.realprice {
		// color: #999999;
		color: #ed4d4f;
		font-size: 24rpx;
		// line-height: 24rpx;
	}
	.isVip {
		text-decoration: line-through;
	}
}
.vip-box {
	background-color: #ed4d4f;
	color: #fff;
	font-size: 20rpx;
	margin-left: 10rpx;
	line-height: 30rpx;
	padding: 0 10rpx;
	border-radius: 25rpx;
}

//扫码按钮
.scan-btn {
	margin: 0% auto;
	width: 70%;
	background-color: #fff;
	padding-top: 50rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
</style>
